package cn.johnyu.account.controller;

import cn.johnyu.account.mapper.AccountMapper;
import cn.johnyu.commons.dto.AccountDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RestController;

import java.lang.management.ManagementFactory;

@RestController
public class AccountController {
    @Autowired
    private AccountMapper accountMapper;
    @GetMapping("/info")
    public String info(){
        String processInfo = ManagementFactory.getRuntimeMXBean().getName();
        String threadInfo = Thread.currentThread().getName();

        return processInfo+ " :: "+threadInfo;

    }

    @GetMapping("/accounts/{id}")
    public AccountDto loadAccount(@PathVariable("id") int id){
        return accountMapper.loadAccount(id);
    }
    @Transactional
    @PutMapping("/reduceBalance")
    public int reduceBalance(int id,int amount){
        int balance = accountMapper.loadAccount(id).getBalance();
        if(amount>balance) throw new RuntimeException("余额不足");
        return accountMapper.reduceBalance(id,amount);
    }
}
